package com.linq.cool.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linq.cool.beauty.domain.BeautyBrand;
import com.linq.cool.beauty.domain.BeautyBrandProductCategory;
import com.linq.cool.beauty.domain.BeautyProductCategory;
import com.linq.cool.beauty.dto.BeautyProductCategoryQueryDTO;
import com.linq.cool.beauty.mapper.BeautyProductCategoryMapper;
import com.linq.cool.beauty.service.BeautyBrandProductCategoryService;
import com.linq.cool.beauty.service.BeautyBrandService;
import com.linq.cool.beauty.service.BeautyProductCategoryService;
import com.linq.cool.beauty.vo.BeautyProductBrandVO;
import com.linq.cool.common.constants.UserConstants;
import com.linq.cool.common.core.exception.BusinessException;
import com.linq.cool.common.core.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: yqlin
 * @Date: 2021/2/1 04:03
 * @Description:
 * @Version: 1.0.0
 */

@Service
public class BeautyProductCategoryServiceImpl extends ServiceImpl<BeautyProductCategoryMapper, BeautyProductCategory> implements BeautyProductCategoryService {

    @Autowired
    private BeautyBrandService beautyBrandService;

    @Autowired
    private BeautyBrandProductCategoryService beautyBrandProductCategoryService;

    @Override
    public IPage<BeautyProductCategory> listByPage(IPage<BeautyProductCategory> page, BeautyProductCategoryQueryDTO dto) {
        return this.page(page, this.getLambdaQueryWrapper(dto));
    }

    @Override
    public List<BeautyProductCategory> listByParams(BeautyProductCategoryQueryDTO dto) {
        return this.list(this.getLambdaQueryWrapper(dto));
    }

    @Override
    public boolean updateProductCategory(BeautyProductCategory productCategory) {
        if (this.checkNameUnique(productCategory)) {
            throw new BusinessException("修改商品分类'" + productCategory.getName() + "'失败，一级分类名称已存在");
        }
        productCategory.setModifier(SecurityUtils.getUserId()).setGmtModified(new Date());
        return this.updateById(productCategory);
    }

    @Override
    public boolean saveProductCategory(BeautyProductCategory productCategory) {
        if (this.checkNameUnique(productCategory)) {
            throw new BusinessException("新增商品分类'" + productCategory.getName() + "'失败，一级分类名称已存在");
        }
        productCategory.setCreator(SecurityUtils.getUserId());
        return this.save(productCategory);
    }

    @Override
    public List<BeautyProductCategory> getSecondLevelProductCategories() {
        // 查询所有一级的
        List<BeautyProductCategory> firstLevelProductCategories = this.list(new LambdaQueryWrapper<BeautyProductCategory>()
                                                                                    .eq(BeautyProductCategory::getLevel, UserConstants.StateEnum.CATEGORY_LEVEL_1.getCode())
        );
        // 查询 所有二级的分类
        List<BeautyProductCategory> secondLevelProductCategories = this.list(new LambdaQueryWrapper<BeautyProductCategory>()
                                                                                     .eq(BeautyProductCategory::getLevel, UserConstants.StateEnum.CATEGORY_LEVEL_2.getCode())
        );
        //        // 查询 所有三级的分类
        //        List<BeautyProductCategory> thirdLevelProductCategories = this.list(new LambdaQueryWrapper<BeautyProductCategory>()
        //                                                                                    .eq(BeautyProductCategory::getLevel, UserConstants.StateEnum.CATEGORY_LEVEL_3.getCode())
        //        );
        // 组装 1->2
        secondLevelProductCategories.forEach(second -> {
            // 遍历一级分类，取出id和second.parentId相同的数据
            BeautyProductCategory parent = firstLevelProductCategories.stream().filter(first -> first.getId().equals(second.getParentId())).findFirst().orElse(null);
            if (parent != null) {
                StringBuilder sb = new StringBuilder();
                second.setName(sb.append(parent.getName()).append(UserConstants.CONCAT_NAME).append(second.getName()).toString());
            }
        });
        //        // 组装 1->2->3
        //        thirdLevelProductCategories.forEach(third -> {
        //            // 遍历二级分类，取出id和third.parentId相同的数据
        //            BeautyProductCategory parent = secondLevelProductCategories.stream().filter(second -> second.getId().equals(third.getParentId())).findFirst().orElse(null);
        //            if (parent != null) {
        //                StringBuilder sb = new StringBuilder();
        //                third.setName(sb.append(parent.getName()).append(UserConstants.CONCAT_NAME).append(third.getName()).toString());
        //            }
        //        });
        return secondLevelProductCategories;
    }

    @Override
    public List<BeautyProductCategory> listByNavStatus() {
        return baseMapper.listByNavStatus();
    }

    @Override
    public BeautyProductBrandVO getProductCategoriesAndBrands(Long productCategoryId) {
        BeautyProductBrandVO vo = new BeautyProductBrandVO();
        // 获取当前商品分类
        BeautyProductCategory curentCategory = this.getById(productCategoryId);
        // 拿到当前商品分类的父id
        Long parentId = curentCategory.getParentId();
        // 根据 parent_id 查询所有 分类
        List<BeautyProductCategory> productCategoryList = this.list(new LambdaQueryWrapper<BeautyProductCategory>()
                                                                            .eq(BeautyProductCategory::getParentId, parentId)
                                                                            .orderByAsc(BeautyProductCategory::getSort)
        );
        // 根据商品分类查询品牌列表 中间表
        // brand_id product_category_id= parentId
        List<BeautyBrandProductCategory> brandProductCategories = beautyBrandProductCategoryService.list(new LambdaQueryWrapper<BeautyBrandProductCategory>()
                                                                                                                 .eq(BeautyBrandProductCategory::getProductCategoryId, parentId)
        );
        if (!CollectionUtils.isNotEmpty(brandProductCategories)) {
            // 根据 brand_id查询所有品牌
            // 取出所有品牌ID
            List<Long> brandIds = brandProductCategories.stream().map(BeautyBrandProductCategory::getBrandId).collect(Collectors.toList());
            List<BeautyBrand> brandList = beautyBrandService.listByIds(brandIds);
            vo.setBrandList(brandList);
        } else {
            vo.setBrandList(new ArrayList<>(0));
        }
        return vo.setProductCategoryList(productCategoryList);
    }


    /**
     * 一级商品分类名称唯一
     *
     * @param productCategory
     *
     * @return
     */
    private boolean checkNameUnique(BeautyProductCategory productCategory) {
        Long productCategoryId = null == productCategory.getId() ? -1L : productCategory.getId();
        BeautyProductCategory one = this.getOne(new LambdaQueryWrapper<BeautyProductCategory>()
                                                        .select(BeautyProductCategory::getId, BeautyProductCategory::getName)
                                                        .eq(BeautyProductCategory::getName, productCategory.getName())
                                                        .eq(BeautyProductCategory::getLevel, UserConstants.StateEnum.CATEGORY_LEVEL_1.getCode())
        );
        // 判断id是否一致 不一致就代表 唯一 false
        return null != one && !productCategoryId.equals(one.getId());
    }


    private LambdaQueryWrapper<BeautyProductCategory> getLambdaQueryWrapper(BeautyProductCategoryQueryDTO dto) {
        return new LambdaQueryWrapper<BeautyProductCategory>()
                .eq(StringUtils.checkValNotNull(dto.getLevel()), BeautyProductCategory::getLevel, dto.getLevel())
                .eq(StringUtils.checkValNotNull(dto.getParentId()), BeautyProductCategory::getParentId, dto.getParentId())
                .eq(StringUtils.checkValNotNull(dto.getNavStatus()), BeautyProductCategory::getNavStatus, dto.getNavStatus())
                .like(StringUtils.checkValNotNull(dto.getName()), BeautyProductCategory::getName, dto.getName())
                .orderByAsc(BeautyProductCategory::getSort)
                ;

    }
}

